package com.ews.onlineexchange.service.schedule;

import java.util.Calendar;
import java.util.Date;
import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import org.hibernate.CacheMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.ews.onlineexchange.model.QualificationCert;
import com.ews.onlineexchange.service.SmsService;

@Singleton
@Startup
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class CertWarnTimer {

	@Resource
	TimerService timerService;
	
	@Inject
	EntityManager entityManager;
	
	@Inject
	SmsService smsService;
	
//	@PostConstruct
	public void init() {
		ScheduleExpression schedule = new ScheduleExpression();	
		schedule.hour(9);
		timerService.createCalendarTimer(schedule, new TimerConfig("certWarnTimer", false));
		
//		check();
	}
	
	private static final String QUERY_ALL_VALID_CERT_EQL = ""
			+ "	SELECT			cert"
			+ "	FROM			QualificationCert cert "
			+ "	WHERE			cert.valid = true 	";
//	@Timeout
	@Schedule(hour="9", minute="0", second="0", info = "certWarnTimer", persistent = false)
	public void check() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + 5);
		Date startingWarnDate = cal.getTime();
		Date now = new Date();
//		Calendar nowCal = Calendar.getInstance();
//		if (nowCal.get(Calendar.HOUR_OF_DAY) - 9 != 0)
//			return;
//		
		Session session = entityManager.unwrap( Session.class );
		ScrollableResults sr = session.createQuery(QUERY_ALL_VALID_CERT_EQL).setCacheMode( CacheMode.IGNORE )
		        .scroll( ScrollMode.FORWARD_ONLY );
		
		while (sr.next()) {
			QualificationCert cert = (QualificationCert) sr.get(0);
			if(null == cert.getAllotedDate()) 
				continue;
			if (cert.getAllotedDate().after(now)
					&& cert.getAllotedDate().before(startingWarnDate)) {
				smsService.addCertExpire(cert);
			}
		}
	}
}
